package dfs;


import java.util.*;

/**
 * https://leetcode.cn/problems/group-anagrams/?favorite=2cktkvj
 */
public class _49_字母异位词分组 {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> resultList = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        int index = 0;
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            String sort = sort(str);
            if (!map.containsKey(sort)) {
                map.put(sort, index);
                index++;
                List<String> result = new ArrayList<>();
                resultList.add(result);
            }
            resultList.get(map.get(sort)).add(str);
        }
        return resultList;
    }


    private String sort(String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}
